package com.zzj.ecology.admin.controller.system;

import com.zzj.ecology.admin.controller.BaseController;
import com.zzj.ecology.common.constant.MenuConstant;
import com.zzj.ecology.common.constant.UrlConstants;
import com.zzj.ecology.common.enums.BusinessType;
import com.zzj.ecology.common.utils.StringUtils;
import com.zzj.ecology.framework.annotation.Log;
import com.zzj.ecology.framework.annotation.RepeatSubmit;
import com.zzj.ecology.system.bean.system.SysMenu;
import com.zzj.ecology.system.bean.vo.dtree.DTreeResponse;
import com.zzj.ecology.system.domain.Page;
import com.zzj.ecology.system.dto.HttpResult;
import com.zzj.ecology.system.service.system.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Api(value = "SysMenuController", description ="SysMenu系统菜单操作相关接口" )
@RestController
@Slf4j
public class SysMenuController extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;


    /**
     * 用户登录后, 获取到用户相应的菜单 菜单delete_status='0'(菜单存在)
     * @param username
     * @return
     */
    @ApiOperation(value = "查询用户菜单", notes = "用户登录后,获取到用户对应的菜单列表", httpMethod = "POST")
    @RequestMapping(value = UrlConstants.MenuUrl.LOGIN_USER_MENU_LIST, method = RequestMethod.POST)
    public HttpResult findOkTabMenuListByUsername(@ApiParam(value = "登录用户账号") String username) {
        if(StringUtils.isEmpty(username)) return HttpResult.error();
        List<SysMenu> list = (List<SysMenu>) sysMenuService.findOkTabMenuListByUsername(username);
        return successData(list);
    }

    /**
     * 查询所有 菜单 下拉框列表 非按钮 数据, 作为表单 非按钮 上级菜单 选项
     * @return
     */
    @ApiOperation(value = "查询菜单下拉列表", notes = "查询菜单下拉框列表数据", httpMethod = "GET")
    @RequestMapping(value = UrlConstants.MenuUrl.SELECTBOX_LIST)
    public HttpResult findNonButtonSelectBoxList() {
        List<SysMenu> list = (List<SysMenu>) sysMenuService.findNonButtonSelectBoxList();
        return successData(list);
    }

    /**
     * laytable分页查询数据
     * @param page
     * @return
     */
    //@PreAuthorize("hasRole(ROLE_fapd)")
    @Deprecated
    @ApiOperation(value = "查询菜单分页数据", notes = "查询菜单分页数据", httpMethod = "GET")
    @RequestMapping(value = UrlConstants.MenuUrl.LIST)
    public HttpResult findPageList(Page page) {
        HttpResult result = sysMenuService.findPageList(page);
        return success(result);
    }


    /**
     * 创建一个新的菜单,并授予初始权限功能。权限前端有提交过来就设置，如果没有提交则不设置
     * @param menu
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "创建菜单", notes = "创建菜单并分配前端提交的初始权限（如果有提交）。默认菜单类型为目录。", httpMethod = "POST")
    @RepeatSubmit
    @Log(title = "菜单管理",businessType = BusinessType.INSERT)
    @PostMapping(value = UrlConstants.MenuUrl.CREATE_AND_GRANT)
    public HttpResult createAndGrant(@Valid SysMenu menu, BindingResult bindingResult, @AuthenticationPrincipal UserDetails userDetails) {
        //System.out.println(menu);
        if(!StringUtils.isEmpty(menu.getType()) && StringUtils.equals( menu.getType(), MenuConstant.MenuType.CATEGORY)){
            menu.setParentId(0);//顶级菜单
        }
        if (menu.getParentId() == null) {
            menu.setParentId(0);
        }
        menu.setCreateBy(userDetails.getUsername());//创建人员
        menu.setCreateAt(new Date());//创建日期
        HttpResult result = sysMenuService.createAndGrant(menu);
        return success(result);
        //return success();
    }

    /**
     * 修改 菜单 的普通信息 或 权限修改信息
     * @param menu
     * @return
     */
    @ApiOperation(value = "修改菜单", notes = "修改菜单普通信息，修改上级菜单及菜单普通字段信息", httpMethod = "POST")
    @RepeatSubmit
    @Log(title = "菜单管理",businessType = BusinessType.UPDATE)
    @PostMapping(value = UrlConstants.MenuUrl.UPDATE_AND_GRANT)
    public HttpResult update(SysMenu menu, @AuthenticationPrincipal UserDetails userDetails) {
        if(null == menu.getMenuId()) return error();
        if(!StringUtils.isEmpty(menu.getType()) && StringUtils.equals( menu.getType(), MenuConstant.MenuType.CATEGORY)){
            menu.setParentId(0);//顶级菜单
        }
        if (menu.getParentId() == null) {
            menu.setParentId(0);
        }
        menu.setUpdateAt(new Date());
        menu.setUpdateBy(userDetails.getUsername());
        HttpResult result = sysMenuService.updateAndGrant(menu);
        return success(result);
    }

    /**
     * 修改菜单权限
     * @param menu
     * @param bindingResult
     * @param userDetails
     * @return
     */
    @ApiOperation(value = "修改菜单权限", notes = "修改菜单权限信息", httpMethod = "POST")
    @RepeatSubmit
    @Log(title = "菜单管理",businessType = BusinessType.GRANT)
    @PostMapping(value = UrlConstants.MenuUrl.RE_PERMS)
    public HttpResult rePerms(@Valid SysMenu menu,
                              BindingResult bindingResult,
                              @AuthenticationPrincipal UserDetails userDetails) {

        if (null == menu.getMenuId()) return error();
        menu.setUpdateAt(new Date());
        menu.setUpdateBy(userDetails.getUsername());
        HttpResult result = sysMenuService.rePerms(menu);
        return success(result);
    }

    /**
     * 查询 当前登录用户 的权限字符串, 以 perms1|perms2|perms3
     * show any button
     * @return
     */
    @ApiOperation(value = "查询用户页面按钮", notes = "查询 当前登录用户 的权限字符串, 以 perms1|perms2|perms3", httpMethod = "POST")
    @PostMapping(value = UrlConstants.MenuUrl.FIND_USER_MENU_BUTTONS)
    public HttpResult findUserMenuPerms(@AuthenticationPrincipal UserDetails userDetails) {
        String username = userDetails.getUsername();
        if(StringUtils.isEmpty(username)) return error();
        List<String> permString = sysMenuService.findUserMenuPermsByUsername(username);
        return successData(permString);
    }


    /**
     *  批量删除菜单数据 ,标记删除,即修改 delete_status = '0' 状态位改成 '1', 记录修改人和修改时间.
     * @param menuids
     * @return
     */
    @ApiOperation(value = "批量删除", notes = "批量删除菜单", httpMethod = "POST")
    @RepeatSubmit
    @Log(title = "菜单管理",businessType = BusinessType.DELETE)
    @PostMapping(value = UrlConstants.MenuUrl.DELETE_BY_IDS)
    public HttpResult updateDeleteStatusByMenuIds(@RequestParam("ids") List<Integer> menuids, @AuthenticationPrincipal UserDetails userDetails) {
        HttpResult result = HttpResult.error();
        if (menuids.size() > 0 && userDetails != null) {
            String username = userDetails.getUsername();
            log.info("menu ids = " + menuids);
            result = sysMenuService.updateDeleteStatusByIds(menuids, username);
        }
        return result;
    }

//    @Deprecated
//    @ApiOperation(value = "菜单树", notes = "查询菜单树形结构", httpMethod = "GET")
//    @RequestMapping(value = UrlConstants.MenuUrl.LAYTREE)
//    public HttpResult laytree() {
//        //HttpResult result = sysMenuService.laytree();
//        return success(result);
//    }

    /**
     * 查询所有未标识删除的 菜单树,delete_status = '0'的状态,基础数据 id, pid 数据
     * @return
     */
    @ApiOperation(value = "菜单树", notes = "查询菜单树形结构", httpMethod = "POST")
    @RequestMapping(value = UrlConstants.MenuUrl.DTREE, method = RequestMethod.POST)
    public DTreeResponse dtree() {
        DTreeResponse dtree = sysMenuService.dtree();
        return dtree;
    }


    /**
     * 菜单管理页面中,展示用页面.查询到的是delete_status='0'(未删)数据的基础数据
     * @return
     */
    @ApiOperation(value = "菜单展示页面",notes = "菜单treeTable页面", httpMethod = "GET")
    @RequestMapping(value = UrlConstants.MenuUrl.TREE_TABLE)
    public HttpResult treeTableDisplay() {
        HttpResult result = sysMenuService.treeTable();
        return success(result);
    }


}
